using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using BlogEngine.Core;

public partial class themes_Refresh_site : System.Web.UI.MasterPage
{
  private StringDictionary settings;

  protected void Page_Load(object sender, EventArgs e)
  {
    settings = GetThemeSettings();

    if (!IsPostBack)
    {  
      ApplyThemeSettings();
    }
  }

  protected string TabClass(string item)
  {
    string outClass = "";
    string path = Request.RawUrl.ToLower();
    if (path.LastIndexOf('/') > -1)
      path = path.Substring(path.LastIndexOf('/') + 1);

    if (item == "Archive" && path == "archive.aspx")
      outClass = "current";

    else if (item == "Contact" && path == "contact.aspx")
      outClass = "current";
    else if (item == "Login" && path.StartsWith("login.aspx"))
      outClass = "current";
    else if (item == "Home" && (path == "default.aspx" || path == ""))
      outClass = "current";
    return outClass;
  }

  private StringDictionary GetThemeSettings()
  {
    StringDictionary temp;
    string dataSource = System.Web.HttpContext.Current.Server.MapPath(BlogSettings.Instance.StorageLocation) + "nonzero.xml";

    // Read them in
    if (!File.Exists(dataSource))
    {
      // No file... Load default settings.
      temp = new StringDictionary();
      temp.Add("isFixedWidth", "false");
      temp.Add("themeColor", "red");
      temp.Add("showColumn2", "true");
      temp.Add("text1Title", "About Me");
      temp.Add("text1Content", "John Doe is a cool cat who uses <a href=\"http://www.dotnetblogengine.net\">BlogEngine.NET</a> for his blog.");
    }
    else
    {
      // Check if it is in the cache already
      temp = (StringDictionary)Cache["nonzero"];

      if (settings == null)
      {
        temp = new StringDictionary();
        LoadSettings(dataSource, temp);
        Cache.Insert("nonzero", temp, new System.Web.Caching.CacheDependency(dataSource));
      }
    }
    return temp;
  }

  private void LoadSettings(string dataSource, StringDictionary settings)
  {
    XmlDocument doc = new XmlDocument();
    doc.Load(dataSource);

    foreach (XmlNode themeNode in doc.SelectSingleNode("Theme").ChildNodes)
    {
      string name = themeNode.Name;
      string value = themeNode.InnerText;

      settings.Add(name, value);
    }
  }

  private void ApplyThemeSettings()
  {
    // Width (Fluid by default)
    DdlThemeLayout.SelectedValue = settings["isFixedWidth"];
    if (settings["isFixedWidth"] == "true")
    {
        main_inner.Attributes.Clear();
        main_inner.Attributes.Add("class", "fixed");
    }
    else
    {
        main_inner.Attributes.Clear();
        main_inner.Attributes.Add("class", "fluid");
    }

    // Set color
    DdlThemeColor.SelectedValue = settings["themeColor"];
    HtmlLink cssLink = new HtmlLink();
    cssLink.Attributes["rel"] = "stylesheet";
    cssLink.Attributes["type"] = "text/css";
    cssLink.Attributes["href"] = "style_" + settings["themeColor"] + ".css";
    Page.Header.Controls.Add(cssLink);

    // Control Column2
    DdlThemeColumns.SelectedValue = settings["showColumn2"];
    if (settings["showColumn2"] == "true")
    {
      Primary.CssClass = "primaryContent_3columns";
      ColumnA.CssClass = "columnA_3columns";
      Sidebar.CssClass = "secondaryContent_3columns";
      ColumnB.Visible = true;
      ColumnC.CssClass = "columnC_3columns";
    }
    else
    {
      Primary.CssClass = "primaryContent_2columns";
      ColumnA.CssClass = "columnA_2columns";
      Sidebar.CssClass = "secondaryContent_2columns";
      ColumnB.Visible = false;
      ColumnC.CssClass = "columnC_2columns";
    }

    // Set Text1
    LblText1Title.Text = settings["text1Title"];
    LblText1Content.Text = settings["text1Content"];
    TxtText1Title.Text = settings["text1Title"];
    TxtText1Content.Text = ConvertToSafe(settings["text1Content"]);
  }

  private string ConvertToSafe(string input)
  {
    string output = Regex.Replace(input, "<", "[[", RegexOptions.None);
    output = Regex.Replace(output, ">", "]]", RegexOptions.None);
    return output;
  }

  private string ConvertToUnsafe(string input)
  {
    string output = Regex.Replace(input, @"\[\[", "<", RegexOptions.None);
    output = Regex.Replace(output, @"\]\]", ">", RegexOptions.None);
    return output;
  }

  private void SaveSettings()
  {
    string dataSource = System.Web.HttpContext.Current.Server.MapPath(BlogSettings.Instance.StorageLocation) + "nonzero.xml";
    using (XmlTextWriter writer = new XmlTextWriter(dataSource, System.Text.Encoding.UTF8))
    {
      writer.Formatting = Formatting.Indented;
      writer.Indentation = 4;
      writer.WriteStartDocument(true);
      writer.WriteStartElement("Theme");

      foreach (string key in settings.Keys)
      {
        writer.WriteElementString(key, settings[key]);
      }

      writer.WriteEndElement();
    }
  }

  protected void BtnTextSave_Click(object sender, EventArgs e)
  {
    LblText1Status.Visible = true;

    settings["text1Title"] = ConvertToUnsafe(TxtText1Title.Text);
    settings["text1Content"] = ConvertToUnsafe(TxtText1Content.Text);

    SaveSettings();
    ApplyThemeSettings();
  }

  protected void BtnSave_Click(object sender, EventArgs e)
  {
    settings["isFixedWidth"] = ConvertToUnsafe(DdlThemeLayout.SelectedValue);
    settings["themeColor"] = ConvertToUnsafe(DdlThemeColor.SelectedValue);
    settings["showColumn2"] = ConvertToUnsafe(DdlThemeColumns.SelectedValue);
    
    SaveSettings();
    ApplyThemeSettings();
  }
}


